package com.cloudm.technician.ui.modules.common.register

import com.cloudm.technician.data.contants.Constant
import com.cloudm.technician.data.db.DbHelper
import com.cloudm.technician.data.model.User
import com.cloudm.technician.data.network.CommonApi
import com.cloudm.technician.data.preferences.PreferencesHelper
import com.cloudm.technician.extensions.isMobile
import com.cloudm.technician.ui.base.RxPresenter
import io.reactivex.Observable
import io.reactivex.Observer
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import java.util.concurrent.TimeUnit

/**
 * 作者: wesley
 * 时间: 2017/12/14
 * 描述: 注册界面的业务逻辑
 */
class RegisterPresenter(private val view: RegisterContract.View, private val commonApi: CommonApi,
                        private val preferencesHelper: PreferencesHelper,
                        private val dbHelper: DbHelper) : RxPresenter(),
        RegisterContract.Presenter {


    private val disposable: CompositeDisposable by lazy {
        CompositeDisposable()
    }

    override fun buildViewByFlag(flag: Int) {
        when (flag) {
            0 -> {
                view.buildTitleRegister()
                view.setServiceAgreementVisible()
            }
            1 -> {
                view.buildTitleFindPassword()
                view.setServiceAgreementGone()
            }
        }
    }


    override fun getVerificationCode(phoneNumber: String?, flag: Int) {
        if (phoneNumber == null || phoneNumber.isNullOrBlank()) {
            view.showInputPhoneNumberMsg()
            return
        }
        if (!phoneNumber.isMobile()) {
            view.showPhoneNumberFormatMsg()
            return
        }
        countDown()
        var status = 1
        when (flag) {
            0 -> status = 1
            1 -> status = 2
        }
        request(commonApi.getVerificationCode(phoneNumber, status), view, onSuccess = { _, _ ->
            view.verificationCodeLoadSuccess(Constant.VERIFICATION_CODE_LOAD_SUCCESS)
        }, onFailure = { errorMsg ->
            view.verificationCodeLoadFailure(errorMsg)
        })
    }


    override fun countDown(time: Long) {
        Observable.intervalRange(1, time, 0, 1, TimeUnit.SECONDS).subscribeOn(
                Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(
                object : Observer<Long> {

                    override fun onSubscribe(d: Disposable) {
                        disposable.add(d)
                    }

                    override fun onComplete() {
                        view.setBtnVericationEnabled()
                    }

                    override fun onNext(t: Long) {
                        view.setBtnVericationNotEnabled(time - t)
                    }

                    override fun onError(e: Throwable) {
                        cancelCountDown()
                        view.setBtnVericationEnabled()
                    }
                })

    }

    override fun registerOrFindPassword(phoneNumber: String?, verification: String?,
                                        password: String?, confirmPassword: String?, flag: Int) {
        if (phoneNumber == null || phoneNumber.isNullOrBlank()) {
            view.showInputPhoneNumberMsg()
            return
        }
        if (!phoneNumber.isMobile()) {
            view.showPhoneNumberFormatMsg()
            return
        }

        if (verification == null || verification.isNullOrEmpty()) {
            view.showVerificationCodeEmptyMsg()
            return
        }

        if (password == null || password.isNullOrEmpty()) {
            view.showPasswordEmptyMsg()
            return
        }

        if (password.length < 6) {
            view.showPasswordLengthMsg()
            return
        }

        if (password != confirmPassword) {
            view.showPasswordNotSameMsg()
            return
        }

        when (flag) {
            0 -> {
                view.showRegisterDialog()
                register(phoneNumber, verification, password)
            }
            1 -> {
                view.showFindPasswordDialog()
                findPassword(phoneNumber, verification, password)
            }
        }
    }


    override fun register(phoneNumber: String, verification: String, password: String) {
        request(commonApi.register(phoneNumber, verification, password), view,
                onSuccess = { user, _ ->
                    view.hideDialog()
                    dealWithUser(user)
                }, onFailure = { errorMsg ->
            view.hideDialog()
            view.showErrorMsg(errorMsg)
        })
    }

    override fun findPassword(phoneNumber: String, verification: String, password: String) {
        request(commonApi.findPassword(phoneNumber, verification, password), view,
                onSuccess = { user, _ ->
                    view.hideDialog()
                    dealWithUser(user)
                }, onFailure = { errorMsg ->
            view.hideDialog()
            view.showErrorMsg(errorMsg)
        })
    }

    override fun cancelCountDown() {
        disposable.clear()
    }


    override fun updateIvClearStatus(type: Int, s: CharSequence?) {
        when (type) {
            0 -> {
                when (s.isNullOrBlank()) {
                    true -> view.clearPhoneNumberInvisible()
                    else -> view.clearPhoneNumberVisible()
                }
            }

            1 -> {
                when (s.isNullOrEmpty()) {
                    true -> view.clearPasswordInVisible()
                    else -> view.clearPasswordVisible()
                }
            }

            2 -> {
                when (s.isNullOrEmpty()) {
                    true -> view.clearPasswordConfirmInVisible()
                    else -> view.clearPasswordConfirmVisible()
                }
            }
        }
    }

    override fun updateIvClearStatus(hasFocus: Boolean, flag: Int) {
        when (hasFocus) {
            true -> {
                when (flag) {
                    0 -> {
                        val number = view.getPhoneNumber()
                        if (number != null && number.trim().isNotEmpty()) {
                            view.clearPhoneNumberVisible()
                        }
                    }
                    1 -> {
                        val password = view.getPassword()
                        if (password != null && password.trim().isNotEmpty()) {
                            view.clearPasswordVisible()
                        }
                    }
                    2 -> {
                        val confirmPassword = view.getPasswordConfirm()
                        if (confirmPassword != null && confirmPassword.trim().isNotEmpty()) {
                            view.clearPasswordConfirmVisible()
                        }
                    }
                }
            }

            false -> {
                when (flag) {
                    0 -> view.clearPhoneNumberInvisible()
                    1 -> view.clearPasswordInVisible()
                    2 -> view.clearPasswordConfirmInVisible()
                }
            }
        }
    }


    private fun dealWithUser(user: User?) {
        when (user) {
            null -> {
                view.showUserEmptyMsg()
            }

            else -> {
                view.registerOrFindPasswordSuccess()
                preferencesHelper.isLogin = true
                preferencesHelper.token = user.token
                preferencesHelper.userId = user.id
                dbHelper.insertOrUpdateUser(user)
            }
        }
    }
}